package com.mianyang.zhangsan.plugin.mail;

import com.mianyang.zhangsan.common.util.FileUtils;
import com.mianyang.zhangsan.exception.SecServiceException;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;

/**
 * @author jiangjr
 * @date 2022-10-26
 */
@Slf4j
@Component
public class MailSender {
    private final JavaMailSenderImpl sender = new JavaMailSenderImpl();

    public void init(String username, String password) {
        sender.setHost("smtp.qq.com");
        sender.setPort(465);
        sender.setProtocol("smtps");
        sender.setUsername(username);
        sender.setPassword(password);
    }

    public void sendMessage(Mail mail) throws MessagingException{
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(mail.getReceive());
        helper.setFrom(mail.getSender());
        helper.setSentDate(new Date());
        helper.setText(mail.getContent());
        helper.setSubject(mail.getSubject());
        MultipartFile[] attachments = mail.getAttachments();
        for (MultipartFile attachment : attachments) {
            attachmentHelper(helper, attachment);
        }
        sender.send(message);
    }

    private void attachmentHelper(MimeMessageHelper helper, MultipartFile file) {
        File local = null;
        try {
            String filePath = FileUtils.convert2File(file);
            local = new File(filePath);
            String fileName = file.getOriginalFilename() == null ? "附件" : file.getOriginalFilename();
            helper.addAttachment(fileName, local);
        } catch (MessagingException e) {
            log.error("邮件附件添加异常---- {}", e.getMessage());
        }
        if (!local.delete()) {
            log.error("文件转化产生的临时文件未删除");
        }
    }
}
